<?php
/**
 * 到账信息队列
 * User: wuhao
 * Date: 2017/4/21
 * Time: 11:29
 */
namespace app\backend\controller\traits;

use app\backend\model\Building;
use app\backend\model\IncomeNotice;
use app\backend\model\Lease;
use app\backend\model\Member;
use app\backend\model\MessageTemplate;
use Business\Business;

trait IncomeNoticeList
{
    /**
     * 生成到账消息队列
     * @date   2017-4-21
     * @author wuhao
     *
     * @param  array  $incomeNotice  支付的数据
     * @param  int    $ordernum      订单号
     * @param  int    $payerId       支付人id
     * @return bool
     */
    public function addIncomeNotice($incomeNotice, $ordernum, $payerId)
    {
        $moneyTypes = load_config('types','money_type');//金额类型
        //dd($incomeNotice);
        if (!$incomeNotice || !is_array($incomeNotice) || !is_numeric($ordernum) || !$payerId) {
            return false;
        }
        $tplModel      = new MessageTemplate();
        $memberModel   = new Member();
        $leaseModel    = new Lease();
        $buildModel    = new Building();

        //获取收款用户的名称,电话信息
        $userId     = array_unique(array_column($incomeNotice, 'mid'));
        $memberInfo = $memberModel->getMemberName($userId);
        //获取付款人用户信息
        $payUserInfo = $memberModel->getMemberName($payerId);
        //获取租赁,到账的模板信息
        $tplPayInfo     = $tplModel->getTemplateByPayOrIncome(1,2,1);//付款方模板
        $tplIncomeInfo  = $tplModel->getTemplateByPayOrIncome(1,2,2);//收款方模板
        if ($tplPayInfo || $tplIncomeInfo) {

            $insertPayerData = $insertOwnerData = [];
            //付款人姓名
            $payer = $payUserInfo['nickname'];
            //缴费时间
            $payTime = time();
            //账单周期
            $beginCycle = $incomeNotice[0]['begin_cycle'];
            $endCycle   = $incomeNotice[0]['end_cycle'];
            //获取房号
            $room = $leaseModel->getLeaseExtByOrderNum($ordernum, 'room');
            $roomstr = '';
            foreach ($room as $r) {
                $roomstr.=$r['room'].',';
            }
            $roomstr = rtrim($roomstr, ',');
            //获取楼宇名称
            $buildName = $buildModel->getBuildingName($incomeNotice[0]['building_id']);

            if ($tplPayInfo) {//付款方要提醒
                $totalMoney = 0;//总金额
                $moneys     = [];//金额类型
                $moneyDetail = '';//金额详情

                //短信头
                $detail = '【租付通】'.$tplPayInfo[0]['title'].'，用户'.$payer.'，您已成功缴费，账单周期'.$beginCycle.'~'.$endCycle.
                    '，楼宇名称'.$buildName['name'].'，房号'.$roomstr.'，总金额为';

                foreach ($incomeNotice as $k => $v) {//生成付款方的到账列表信息
                    //详情
                    if (isset($moneys[$v['type_money']])) {
                        $moneys[$v['type_money']] += intval($v['money']);
                    } else {
                        $moneys[$v['type_money']] = intval($v['money']);
                    }
                    //总金额
                    $totalMoney += $v['money'];
                }

                foreach ($moneys as $a => $m) {
                    if ($a == 9) {//优惠就是金额
                        $moneyDetail .= $moneyTypes[$a] . ' ' . yuan($m)*(-1) . '元,';
                    } else {
                        $moneyDetail .= $moneyTypes[$a] . ' ' . yuan($m) . '元,';
                    }
                }
                $moneyDetail            = rtrim($moneyDetail, ',');
                $detail.=yuan($totalMoney).'元，账单明细'.$moneyDetail.'，缴费时间'.date('Y-m-d H:i:s');
                $insertPayerData[] = [
                    'mid'           => 0,//收款人
                    'payer_id'      => $payUserInfo['id'],//付款人
                    'owner_name'    => 0,//付款人不显示收款对象
                    'payer_name'    => $payer,//付款人姓名
                    'mobile'        => $payUserInfo['mobile'],
                    'send_member'   => 1,
                    'begin_cycle'   => $beginCycle,
                    'end_cycle'     => $endCycle,
                    'money'         => $totalMoney,
                    'ordernum'      => $ordernum,
                    'message_type'  => $tplPayInfo[0]['message_type'],
                    'notify_method' => $tplPayInfo[0]['notify_method'],
                    'send_type'     => $tplPayInfo[0]['send_type'],
                    //'room'          => $rooms,
                    'pay_time'      => $payTime,
                    'money_detail'  => $moneyDetail,
                    'detail'        => $detail,
                    'priority'      => 1,
                    'send_time'     => 0,
                    'send_status'   => 0,
                    'create_time'   => time(),
                    'update_time'   => time(),
                ];
                unset($detail);
            }

            if ($tplIncomeInfo) {//收款方要提醒
                $moneys = [];
                foreach ($incomeNotice as $key => $value) {//生成到账人信息
                    //收款付款人姓名
                    foreach ($memberInfo as $m) {
                        if ($m['id'] == $value['mid']) {
                            $owner        = $m['nickname'];
                            $incomeMobile = $m['mobile'];
                            break;
                        }
                    }

                    //详情
                    $moneyDetail = '';//金额详情
                    $type   = getMoneyType($value['type_money']);
                    $money  = yuan($value['money']);

                    unset($type, $money);

                    if (!isset($moneys[$value['mid']])) {
                        $moneys[$value['mid']]['money_detail'] = $moneyDetail;
                        $moneys[$value['mid']]['total']  = (int) $value['money'];
                        $moneys[$value['mid']]['mobile'] = $incomeMobile;
                        $moneys[$value['mid']]['owner_name'] = $owner;
                        $moneys[$value['mid']]['mid'] = $value['mid'];

                    } else {
                        $moneys[$value['mid']]['money_detail'] .= $moneyDetail;
                        $moneys[$value['mid']]['total']  += (int) $value['money'];
                    }
                }
                //遍历付款对象
                foreach ($moneys as $a => $b) {
                    $detail =  '【租付通】'.$tplIncomeInfo[0]['title'].'，收款方'.$b['owner_name'].'，付款方'.$payer.'，周期'.$beginCycle.'~'.$endCycle.
                        '，楼宇名称'.$buildName['name'].
                        '房号'.$roomstr.
                        '，总金额为'.yuan($b['total']).'元，账单明细'.rtrim($b['money_detail'], ',').'，缴费时间'.date('Y-m-d H:i:s');
                    $insertOwnerData[] = [
                        'mid'           => $b['mid'],//收款人
                        'payer_id'      => $payUserInfo['id'],//付款人
                        'owner_name'    => $b['owner_name'],//收款对象
                        'payer_name'    => $payer,//付款人姓名
                        'mobile'        => $b['mobile'],
                        'send_member'   => 2,
                        'begin_cycle'   => $beginCycle,
                        'end_cycle'     => $endCycle,
                        'money'         => $b['total'],
                        'ordernum'      => $ordernum,
                        'message_type'  => $tplIncomeInfo[0]['message_type'],
                        'notify_method' => $tplIncomeInfo[0]['notify_method'],
                        'send_type'     => $tplIncomeInfo[0]['send_type'],
                        //'room'          => $rooms,
                        'pay_time'      => $payTime,
                        'money_detail'  => rtrim($b['money_detail'], ','),
                        'detail'        => $detail,
                        'priority'      => 1,
                        'send_time'     => 0,
                        'send_status'   => 0,
                        'create_time'   => time(),
                        'update_time'   => time(),
                    ];
                    unset($detail);
                }
            }

            //合并，插入数据
            $insertData  = array_merge($insertOwnerData, $insertPayerData);
            $incomeNoticeModel = new IncomeNotice();
            if (!$incomeNoticeModel->add($insertData)) {
                zft_log('incomeNotice/add', $incomeNoticeModel->getLastSql());
                return false;
            } else {
                return true;
            }
        } else {
            zft_log('incomeNotice/add', '未配置消息模板--'.$tplModel->getLastSql());
            return false;
        }
    }

    /**
     * 获取到账消息队列
     * @date   2017-4-26
     * @author wuhao
     *
     * @param  int    $ordernum      订单号
     * @param  int    $beginCycle    开始周期 20170501
     * @param  int    $endCycle      结束周期
     * @param  int    $notifyMethod  通知方式 1=短信 2=邮件 3=系统弹窗 0=所有
     * @param  int    $messageType   消息类型  1: 公告 2: 提醒 3：信息 0=所有
     * @param  int    $sendStatus    发送状态  0未发送  1已发送
     * @return mixed
     */
    public function getIncomeNotice($ordernum, $beginCycle, $endCycle, $notifyMethod = 0, $messageType = 0, $sendStatus)
    {
        if (!$ordernum || !$beginCycle || !$endCycle || !in_array($notifyMethod, [0,1,2,3]) || !in_array($messageType, [0,1,2,3]) || !in_array($sendStatus, [0,1])) {
            return false;
        }
        $incomeNoticeModel = new IncomeNotice();
        $res = $incomeNoticeModel->getList($ordernum, $beginCycle, $endCycle, $notifyMethod, $messageType, $sendStatus);
        return $res;
    }

    /**
     * 发送短信
     * @date   2017-4-26
     * @author wuhao
     *
     * @param  array    $smsList      短信列表
     * @param  array    $roomArr      对应房号
     * @param  string   $buildingName  对应楼宇名称
     * @return array 发送成功的短信id
     */
    public function sendSms($smsList, $roomArr, $buildingName = '')
    {
        $idArr = [];
        //先获取模板内容
        $tplModel = new MessageTemplate();
        $memberModel = new Member();
        //获取租赁,到账的模板信息
        $tplPayInfo     = $tplModel->getTemplateByPayOrIncome(1,2,1);//付款方模板
        $tplIncomeInfo  = $tplModel->getTemplateByPayOrIncome(1,2,2);//收款方模板
        $business       = new Business();
        $rooms = implode(',', $roomArr);
        foreach ($smsList as $k => $sms) {
            if ($sms['send_member'] == 1) {//发给付款人
                if ($tplPayInfo) {
                    $content = json_decode($tplPayInfo[0]['content'], true);//
                    //获取付款人手机号
                    $mInfo = $memberModel->getMemberInfoById($sms['payer_id'], 'mobile');
                    $mobile = $mInfo['mobile'];//发送对象
                    $datas[0] = $tplPayInfo[0]['title'];
                    $datas[1] = $datas[2] = $datas[3] = $datas[4] = '';
                    $datas[1] = $sms['begin_cycle'].'~'.$sms['end_cycle'];
                    $datas[2] = $rooms;
                    $datas[3] = yuan($sms['money']).'元';
                    $datas[4] = $sms['money_detail'];
                    $datas[5] = date('Y-m-d H:i:s', $sms['pay_time']);
                    $datas[6] = $sms['payer_name'];//付款人姓名
                    $datas[7] = $sms['owner_name'];//收款人姓名
                    $datas[8] = $buildingName;  //楼宇名称
                    $res = $business->sendIncomeNotice($mobile, $datas, $content, 1, 1);
                    if ($res['code'] == 200) {
                        $idArr[] = $sms['id'];//发送成功， 保存其id
                    }
                }
            } else { //发送给收款人
                if ($tplIncomeInfo) {
                    $content = json_decode($tplIncomeInfo[0]['content'], true);//模板内容
                    //获取收款人手机号
                    $mInfo = $memberModel->getMemberInfoById($sms['mid'], 'mobile');
                    $mobile = $mInfo['mobile'];//发送对象
                    $datas[0] = $tplIncomeInfo[0]['title'];
                    $datas[1] = $datas[2] = $datas[3] = $datas[4] = '';
                    $datas[1] = $sms['begin_cycle'].'~'.$sms['end_cycle'];
                    $datas[2] = $rooms;
                    $datas[3] = yuan($sms['money']).'元';
                    $datas[4] = $sms['money_detail'];
                    $datas[5] = date('Y-m-d H:i:s', $sms['pay_time']);
                    $datas[6] = $sms['payer_name'];//付款人姓名
                    $datas[7] = $sms['owner_name'];//收款人姓名
                    $datas[8] = $buildingName;  //楼宇名称
                    $res = $business->sendIncomeNotice($mobile, $datas, $content, 1, 2);
                    if ($res['code'] == 200) {
                        $idArr[] = $sms['id'];
                    }
                }
            }
        }
        return $idArr;
    }

    /**
     * 更新短信状态
     * @date   2017-4-26
     * @author wuhao
     *
     * @param  int|array  $id         id或id数组
     * @param  int        $sendStatus 发送状态 1=发送成功
     * @param  int        $sendTime   发送时间
     * @return bool
     */
    public function updateSendStatus($id, $sendStatus = 1, $sendTime)
    {
        if (!$id || (!is_numeric($id) && !is_array($id)) || !in_array($sendStatus, [0,1]) || !$sendTime) {
            return false;
        }
        $incomeNoticeModel = new IncomeNotice();
        $res = $incomeNoticeModel->updateSendStatus($id, $sendStatus = 1, $sendTime);
        if (!$res) {
            zft_log('incomeNotice/update', $incomeNoticeModel->getLastSql());
            return false;
        } else {
            return true;
        }
    }
}